#!/usr/bin/env python
# coding=utf8
"""
@summary: 从hadoop上将文件读出来，并且转化region字段；最后发送邮件
@attention: 从hadoop上将文件读出来，并且转化region字段；最后发送邮件
@author: hongxingfan
@since: 2014年8月7日	下午3:36:42
"""
from email.mime.text import MIMEText
import smtplib
  
def send_mail(mail_host, from_1, to_list, sub, content):  # to_list：收件人；sub：主题；content：邮件内容
	#cbg-data@baidu.com
	msg = MIMEText(content, _subtype = "html", _charset = "utf-8")  # 创建一个实例，这里设置为文本格式邮件
	msg["Subject"] = sub  # 设置主题
	msg["From"] = from_1
	msg["To"] = ";".join(to_list)
	msg["Accept-Language"] = "zh-CN"
	msg["Accept-Charset"] = "ISO-8859-1,utf-8"
	try:
		smtp = smtplib.SMTP()
		smtp.connect(mail_host)
		smtp.sendmail(from_1, to_list, msg.as_string())  # 发送邮件
		smtp.close()
		return True
	except Exception, e:
		print str(e)
		return False
if __name__ == "__main__":
	mail_host = "mail1-in.baidu.com"  # 设置服务器
	from_1 = "noah-autopost@baidu.com"
	to_list = ["fanhongxing@baidu.com"]
	#to_list = ["fanhongxing@baidu.com","baiyunlong@baidu.com","wangshaoxin@baidu.com","sidongdong@baidu.com"]
	import commands
	import datetime
	import time
	lastDate = (datetime.date.today() - datetime.timedelta(days = 1)).strftime("%Y%m%d")
	now =  time.strftime("%Y-%m-%d %X", time.localtime())
	hadoop = "hadoop dfs -ls /app/passport/pass_data/pass_data.db/ssn_log/*/dt=" + lastDate
	(a,b) = commands.getstatusoutput(hadoop)
	message = "<html><body><table border='2'><tr>"
	message += "<td>" + "表名" + "</td>"
	message += "<td>" + "监控日期" + "</td>"
	message += "<td>" + "此刻时间" + "</td>"
	message += "<td>" + "状态" + "</td>"
	message += "</tr>"
	if a != 0:
		message += "<tr>"
		message += "<td>" + "ssn_log" + "</td>"
		message += "<td>" + lastDate + "</td>"
		message += "<td>" + now + "</td>"
		message += "<td>" + "NOT FOUND" + "</td>"
		message += "</tr>"
	hadoop = "hadoop dfs -ls /app/passport/pass_data/pass_data.db/login_log/dt=" + lastDate
	(c,b) = commands.getstatusoutput(hadoop)
	if c != 0:
		message += "<tr>"
		message += "<td>" + "login_log" + "</td>"
		message += "<td>" + lastDate + "</td>"
		message += "<td>" + now + "</td>"
		message += "<td>" + "NOT FOUND" + "</td>"
		message += "</tr>"
	hadoop = "hadoop dfs -ls /app/passport/pass_data/pass_data.db/reg_log/dt=" + lastDate
	(d,b) = commands.getstatusoutput(hadoop)
	if d != 0:
		message += "<tr>"
		message += "<td>" + "reg_log" + "</td>"
		message += "<td>" + lastDate + "</td>"
		message += "<td>" + now + "</td>"
		message += "<td>" + "NOT FOUND" + "</td>"
		message += "</tr>"
	message += "</table></body></html>"
	sub = "ssn_log,login_log,reg_log 日志监控"
	if a != 0 or c != 0 or d != 0:
		send_mail(mail_host, from_1, to_list, sub, message)
